package com.sxkf.core.third.os.impl;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.sxkf.core.third.os.OsConstant;
import com.sxkf.core.third.os.OsService;
import com.sxkf.core.third.os.vo.response.UploadFileVO;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description 腾讯COS存储
 * @Author Eliauk
 * @Date 2023/5/26 4:50 PM
 */
@Data
@Service
@ConfigurationProperties(prefix = "tencent-cos")
@JsonInclude(value = JsonInclude.Include.NON_NULL)
@ApiModel(value = "CosService实现类", description = "CosService实现类对象")
public class CosServiceImpl implements OsService {
    private static final Logger logger = LoggerFactory.getLogger(CosServiceImpl.class);

    /**
     * 上传文件
     *
     * @param file 文件
     * @return UploadFileVO
     */
    @Override
    public UploadFileVO uploadFile(MultipartFile file) throws IOException {
        //临时文件路径
        String temporaryFile = String.format(OsConstant.OS_FILE_PATH, OsConstant.APPLICATION_NAME);
        //效验临时文件是否存在
        File localFile = new File(temporaryFile);
        if (!localFile.exists()) {
            //临时文件不存在，创造临时文件
            boolean mkdir = localFile.mkdirs();
            System.out.println(mkdir);
        }
        //创造临时文件名称
        String originalFilename = file.getOriginalFilename();
        String fileName;
        if (StrUtil.isNotBlank(originalFilename)) {
            fileName = originalFilename;

        } else {
            fileName = file.getName() + ".png";
        }
        assert fileName != null;
        String name = "/" + RandomStringUtils.randomNumeric(6) + System.currentTimeMillis() + System.nanoTime() + RandomStringUtils.randomNumeric(6) + fileName.substring(fileName.lastIndexOf('.'));
        //创造临时文件图片
        temporaryFile = temporaryFile + name;
        FileOutputStream fos;
        fos = new FileOutputStream(temporaryFile);
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        File cosFile = new File(temporaryFile);
        COSCredentials cred = new BasicCOSCredentials(OsConstant.KEY, OsConstant.SECRET);
        Region region = new Region(OsConstant.REGION_NAME);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(cred, clientConfig);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        PutObjectRequest putObjectRequest = new PutObjectRequest(OsConstant.BUCKET_NAME, temporaryFile + sdf.format(new Date()) + name, cosFile);
        cosClient.putObject(putObjectRequest);
        String saveUrl = OsConstant.ACCESS_URL + putObjectRequest.getKey();
        File localImgFile = new File(temporaryFile);
        boolean delete = localImgFile.delete();
        if (delete) {
            logger.info("删除成功");
        }
        UploadFileVO uploadFileVO = new UploadFileVO();
        uploadFileVO.setUrl(saveUrl);
        return uploadFileVO;
    }
}

